package com.bucks.services;

import com.bucks.bean.Coffee;
import com.bucks.repository.CoffeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

/**

 * @date 2019-11-12
 */
@Slf4j
@Service
public class CoffeeService {

    @Autowired
    private CoffeeRepository coffeeRepository;


    public void initMenu(){
        Coffee espresso = Coffee.builder().name("espresso")
                .price(Money.of(CurrencyUnit.of("CNY"),20.0)).build();
        coffeeRepository.save(espresso);

        Coffee latte = Coffee.builder().name("latte")
                .price(Money.of(CurrencyUnit.of("CNY"),35.0)).build();
        coffeeRepository.save(latte);

        Coffee americano = Coffee.builder().name("americano")
                .price(Money.of(CurrencyUnit.of("CNY"),33.0)).build();
        coffeeRepository.save(americano);
        coffeeRepository.saveAll(Arrays.asList(espresso,latte,americano));
    }

    public List<Coffee> findAllCoffee(){
        initMenu();
        return coffeeRepository.findAll();
    }

    public Optional<Coffee> findOneCoffee(String name){
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name",exact().ignoreCase());
        Optional<Coffee> coffee = coffeeRepository.findOne(
                Example.of(Coffee.builder().name(name).build(),matcher));
        log.info("Coffee Found: {}",coffee);
        return coffee;
    }
}
